package com.basis.eventHandler;

import com.basis.service.DCInputPageService;
import com.mes.data.EmesDcInputData;
import org.openbravo.base.exception.OBException;
import org.openbravo.base.model.Entity;
import org.openbravo.base.model.ModelProvider;
import org.openbravo.client.kernel.event.EntityDeleteEvent;
import org.openbravo.client.kernel.event.EntityNewEvent;
import org.openbravo.client.kernel.event.EntityPersistenceEventObserver;
import org.openbravo.client.kernel.event.EntityUpdateEvent;
import org.openbravo.dal.core.OBContext;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.service.db.DalConnectionProvider;
import javax.enterprise.event.Observes;

/**
 * 数据采集页面监听SQL字段
 * @author zt
 */
public class DCInputPageEventHandler extends EntityPersistenceEventObserver {
	@Override
	protected Entity[] getObservedEntities() {
		return new Entity[]{ ModelProvider.getInstance().getEntity(EmesDcInputData.ENTITY_NAME)};
	}
	
	public void onSave(@Observes EntityNewEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
		EmesDcInputData ds = (EmesDcInputData)event.getTargetInstance();
		checkColumnAndParams(ds);
	}
	
	public void onUpdate(@Observes EntityUpdateEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
		EmesDcInputData ds = (EmesDcInputData)event.getTargetInstance();
		checkColumnAndParams(ds);
	}

	public void onDelete(@Observes EntityDeleteEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
		EmesDcInputData ds = (EmesDcInputData)event.getTargetInstance();
		if (!ds.getEmesDcInputDataDetailList().isEmpty()) {
			//throwMessage("数据源下有字段信息，请先删除字段信息，然后再");
		}
	}

	private void checkColumnAndParams(EmesDcInputData ds) {
		try {
			DCInputPageService service = new DCInputPageService();
			service.parseSqlColumnAndParams(ds);
		} catch (Exception e) {
			e.printStackTrace();
			throwMessage(e.getMessage());
		}
	}

	private void throwMessage(String message){
		String language = OBContext.getOBContext().getLanguage().getLanguage();
		ConnectionProvider conn = new DalConnectionProvider(false);
		throw new OBException(Utility.messageBD(conn, message, language));
	}
}
